package com.jahentao.integrationTest.case07;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;

import com.jahentao.integrationTest.case07.entity.Ticket;

/**
 * 模拟售票应用
 * @author jahentao
 * @date 2018-5-13
 *
 */
public class App implements Runnable{
	
	/** 模拟服务器 */
	private static ServerSocket serverSocket;
	/** 线程池，线程池中的线程处理客户端连接 */
	private static final ExecutorService pool = Executors.newFixedThreadPool(10); // 接收用户请求的线程池固定为10个;
	
	@Override
	public void run() {
		try {
		    for (;;) {
		        pool.execute(new Handler(serverSocket.accept()));
		    }
		} catch (IOException ex) {
		    pool.shutdown();
		}
	}
	
	/**
	 * 处理一个客户端买票请求
	 * @author jahentao
	 * @date 2018-5-14
	 */
	class Handler implements Runnable {
		
		private final Socket socket;
		
		Handler(Socket socket) {
			this.socket = socket;
		}
		
		@Override
		public void run() {
			// TODO
			System.out.println(Thread.currentThread().getName() + " 卖了一张票");
		}
	}
	
    public static void main(String[] args) {
    	// 初始化 票种和票数
        Ticket ticket1 = new Ticket("复仇者联盟3：无尽战争", 100);
        Ticket ticket2 = new Ticket("头号玩家", 200);
        
        Map<String, Ticket> ticketMap = new HashMap<>();
        ticketMap.put("复仇者联盟3：无尽战争", ticket1);
        ticketMap.put("头号玩家", ticket2);
        Map<String, Ticket> unmodifiableMap = Collections.unmodifiableMap(ticketMap);
        
        TicketBookingModule ticketBookingModule;
        TicketRefundModule ticketRefundModule;
        
        // 初始化App
        App app = new App();
        
        try {
			serverSocket = new ServerSocket(8090);// 请确保8090端口没有被占用
		} catch (IOException e) {
			System.out.println("端口被占用");
			e.printStackTrace();
		} 
        
        new Thread(app).start(); // 启动应用
        
        // 初始化 购票模块和退票模块
        try {
			ticketBookingModule = new TicketBookingModule(5); // 模拟，5个卖票线程
//			ticketBookingModule
			ticketRefundModule = new TicketRefundModule(1); // 模拟，1个退票线程
		} catch (IOException e) {
			System.out.println("购票模块初始化失败");
			e.printStackTrace();
		}
        
        
    }
    
}
